// 多场投票后台管理页面逻辑
let token = '';
let currentVoteId = null;

const loginSection = document.getElementById('loginSection');
const adminPanel = document.getElementById('adminPanel');
const loginForm = document.getElementById('loginForm');
const loginFeedback = document.getElementById('loginFeedback');
const optionsForm = document.getElementById('optionsForm');
const optionsInput = document.getElementById('optionsInput');
const timeForm = document.getElementById('timeForm');
const startTime = document.getElementById('startTime');
const endTime = document.getElementById('endTime');
const resultsDiv = document.getElementById('results');
const refreshResultsBtn = document.getElementById('refreshResults');
const exportBtn = document.getElementById('exportBtn');
const adminFeedback = document.getElementById('adminFeedback');
const startVoteBtn = document.getElementById('startVoteBtn');

// 新表单和列表元素
const createVoteForm = document.getElementById('createVoteForm');
const newVoteName = document.getElementById('newVoteName');
const newVoteOptions = document.getElementById('newVoteOptions');
const newVoteStart = document.getElementById('newVoteStart');
const newVoteEnd = document.getElementById('newVoteEnd');
const voteListUl = document.getElementById('voteListUl');
const refreshVoteListBtn = document.getElementById('refreshVoteList');
const voteDetailCard = document.getElementById('voteDetailCard');
const voteDetailTitle = document.getElementById('voteDetailTitle');

function showLogin(show) {
  loginSection.style.display = show ? '' : 'none';
  adminPanel.style.display = show ? 'none' : '';
}

function showFeedback(el, msg, type = 'info') {
  el.textContent = msg;
  el.className = `feedback ${type}`;
}

loginForm.onsubmit = async (e) => {
  e.preventDefault();
  showFeedback(loginFeedback, '登录中...');
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  try {
    const res = await fetch('/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    });
    if (!res.ok) throw new Error('账号或密码错误');
    const data = await res.json();
    token = data.token;
    showLogin(false);
    await loadVoteList();
  } catch (err) {
    showFeedback(loginFeedback, err.message, 'error');
  }
};

// 新建投票（填写名称、选项、时间后提交）
createVoteForm.onsubmit = async (e) => {
  e.preventDefault();
  const name = newVoteName.value.trim();
  const options = newVoteOptions.value.split('\n').map(s => s.trim()).filter(Boolean);
  const start = newVoteStart.value;
  const end = newVoteEnd.value;
  if (!name || !options.length || !start || !end) {
    showFeedback(adminFeedback, '请填写完整信息', 'error');
    return;
  }
  try {
    const res = await fetch('/api/votes', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
      body: JSON.stringify({ name, options, start, end })
    });
    if (!res.ok) throw new Error('新建失败');
    await loadVoteList();
    showFeedback(adminFeedback, '新建投票成功', 'success');
    createVoteForm.reset();
  } catch (err) {
    showFeedback(adminFeedback, err.message, 'error');
  }
};

// 加载投票列表
async function loadVoteList() {
  voteListUl.innerHTML = '加载中...';
  const res = await fetch('/api/votes', { headers: { 'Authorization': 'Bearer ' + token } });
  const data = await res.json();
  voteListUl.innerHTML = '';
  data.forEach(vote => {
    const li = document.createElement('li');
    li.style = 'margin-bottom:4px;';
    li.innerHTML = `<a href="#" data-id="${vote.id}">${vote.name}</a> <span style="color:#888;font-size:12px;">(${vote.status})</span> <a href="/scoreboard.html?voteId=${vote.id}" target="_blank" style="font-size:12px;">[大屏]</a> <a href="/vote.html?voteId=${vote.id}" target="_blank" style="font-size:12px;">[投票页]</a>`;
    li.querySelector('a[data-id]').onclick = (ev) => { ev.preventDefault(); selectVote(vote.id); };
    voteListUl.appendChild(li);
  });
}
refreshVoteListBtn.onclick = loadVoteList;

// 查看投票详情
async function selectVote(voteId) {
  currentVoteId = voteId;
  voteDetailCard.style.display = '';
  // 加载详情
  const res = await fetch(`/api/votes/${voteId}`, { headers: { 'Authorization': 'Bearer ' + token } });
  const data = await res.json();
  voteDetailTitle.textContent = data.name || '投票详情';
  await loadResults();
}



async function loadResults() {
  if (!currentVoteId) return;
  const res = await fetch(`/api/votes/${currentVoteId}/results`);
  const data = await res.json();
  resultsDiv.innerHTML = data.map(opt => `<div>${opt.name}：${opt.count}票</div>`).join('');
}

refreshResultsBtn.onclick = loadResults;

exportBtn.onclick = async () => {
  if (!currentVoteId) return;
  try {
    const res = await fetch(`/api/votes/${currentVoteId}/export`, {
      headers: { 'Authorization': 'Bearer ' + token }
    });
    if (!res.ok) throw new Error('导出失败');
    const data = await res.json();
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `votes_${currentVoteId}.json`;
    a.click();
    URL.revokeObjectURL(url);
  } catch (err) {
    showFeedback(adminFeedback, err.message, 'error');
  }
};

showLogin(true);
voteDetailCard.style.display = 'none';
